<%@ page language="java" import="java.util.*,java.sql.*,model.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'doLogin.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>    
  <%
  
  String userName = request.getParameter("userName");
  String userPwd = request.getParameter("userPwd") ;
  
   if(request.getParameter("chkRemember")==null){
   	 //如何清除系统记住的cookie
     Cookie cookie = new Cookie("userName",userName);    
   	 cookie.setMaxAge(0);//将时间设置为0，cookie就会马上失效
   	 response.addCookie(cookie);
   	  
   }else{
    //使用cookie记住用户名和密码
   	 Cookie cookie = new Cookie("userName",userName);
   	 cookie.setMaxAge(90);
   	 response.addCookie(cookie);
   	 cookie = new Cookie("userPwd",userPwd);
   	 cookie.setMaxAge(90);
   	 response.addCookie(cookie);
   }
   
  try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String url = "jdbc:mysql://localhost:3306/newsdb";
		String user = "root";
		String password = "root";
		Connection con=null;
		try {
			//get connection
			con = DriverManager.getConnection(url, user, password);
			//get statement
			Statement st = con.createStatement();
			//get user login sql
			String sql = "select * from userinfo where userName='"+userName+"'";
			sql += " and userpwd='"+userPwd+"'";
			ResultSet rs = st.executeQuery(sql);
			if(rs.next()){
			    //登录成功后，跳转到ListNews.jsp,在该页面显示出欢迎+userName
			    //方式一，页面重定向，要传递的内容需要自己在url里面拼接
			    //response.sendRedirect("ListNews.jsp?userName="+userName+"&realname=");
			    //方式二，内部跳转，要传递的内容，request会携带过去
			    //request.getRequestDispatcher("ListNews.jsp").forward(request, response);
				UserInfo ui = new UserInfo();
				ui.setId(rs.getInt(1));
				ui.setUserName(rs.getString(2));
				ui.setUserPwd(rs.getString(3));
				session.setAttribute("userInfo", ui);//将登录状态信息放入session
				response.sendRedirect("ListNews.jsp");
				out.println("登陆成功");
			}else{
				out.println("用户名或密码错误，请重新登陆");
			}
			rs.close();
			st.close();
			con.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
  
   %>
  </body>
</html>
